import 'package:FineArt/init/navigation_service.dart';
import 'package:FineArt/page/Login/login_screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../../utils/sputils.dart';

class AuthInterceptor extends Interceptor {
  @override
  Future onRequest(RequestOptions options) async {
    String auth = await SPUtils.getToken();
    if (auth != null && auth.isNotEmpty) {
      options.headers.addAll({'Authorization': auth});
    }
    return options;
  }

  // @override
  // Future onResponse(Response response) {
  //   int code = response.data["code"];
  //   if (code == 502)
  //     {
  //       String role = SPUtils.getRole();
  //       Navigator.of(NavigationService.navigatorKey.currentContext)
  //           .push(MaterialPageRoute(builder: (context) {
  //         return LoginScreen(role);
  //       }));
  //     }
  //   else
  //   // TODO: implement onResponse
  //   return super.onResponse(response);
  // }

  @override
  Future onError(DioError err) {
    if (err.response?.statusCode == 777 || err.response?.statusCode == 776)
    {
      String role = SPUtils.getRole();
      Navigator.of(NavigationService.navigatorKey.currentContext)
          .pushAndRemoveUntil(MaterialPageRoute(builder: (context) {
        return LoginScreen(role);
      }),(Route<dynamic> route) => false);
    }
    // TODO: implement onError
    return super.onError(err);
  }
}
